﻿
(function() {
	var fileDivName = 'FileDiv';
	var editCanvas = null;
	var editContext = null;
	var picCanvas = document.createElement('canvas');
	var picScale = 1;
	var picRotateAngle = 0;
	var mouseStarted = false;
	var preXPos = 0;
	var preYPos = 0;
	var oldTwoTouchDis = 0;
	var oldTouchAngle = 0;
	var oldCenterX = 0;
	var oldCenterY = 0;
	var picPosX = 0;
	var picPosY = 0;
	var picWidth = 0;
	var picHeight = 0;
	
	var centerMaskImage = null;
	var centerMaskImageList = [];
	var frameMaskImage = new Image();
	var curSelectMaskIndex = 0;
	var maskAlpha = 122;
	var maskCanvas = null;
	var maskContext = null;
	
	var picAreaWidth = 0;
	var picAreaHeight = 0;
	
	var picClipLeft = 0;
	var picClipTop = 0;
	var picClipWidth = 0;
	var picClipHeight = 0;
	
	var clipAreaLengthWidthRatio = 1;
	var clipAreaSizeR = 0.8;
	var clipPicWidth = 222;
	var picLoading = false;
	
	var system = {
		win: false, mac: false, xll: false
	};

	
	function init() {
		createWindow();
		fitWindow();
		bindEvent();
	}

    var browser={
        versions:function() {
            var u=navigator.userAgent, app = navigator.appVersion;
            return {//移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
            };
        }(),
        language:(navigator.browserLanguage || navigator.language).toLowerCase()
    }

	function createWindow() {
		var fileDiv = document.createElement("div");
		document.body.appendChild(fileDiv);
		
		fileDiv.id = fileDivName;
		fileDiv.style.position = "fixed";
		
		fileDiv.style.left = '0%';
		fileDiv.style.width = '100%';
		fileDiv.style.top = '0%';
		fileDiv.style.height = '100%';

		var buttonStyle =
			"text-shadow: 0px 0px 0 #2e2d2d;" +
			"border: 1px solid transparent;;" +
			"border-top-left-radius: 5px;" +
			"border-top-right-radius: 5px;" +
			"border-bottom-left-radius: 5px;" +
			"border-bottom-right-radius: 5px;" +
			"font-size: 1.0rem;" +
			"position:absolute;";
            if (browser.versions.android)
            {
                fileDiv.innerHTML =
                    '<div style="position:absolute;left: 0; top: 0; bottom: 0; right: 0;" id="PicArea" >' +
                    '<canvas id="EditCanvas" style="background-image: url(images/buttonStyle.png); display: block ;position:absolute; left:0%; width:100%; top:0%; height:100%;"></canvas>' +
                    '<input id="Cancel2" type="button" value="取消" style="' + buttonStyle + 'right:0;width: 3.5rem; top:5%; color:white;height:2rem;font-size: 1rem;background-image: url(images/buttonStyle.png);background-size:cover;"/>' +
                    '</div>' +
                    '<div style="position:absolute; left:0%; width:100%;bottom: 0; height: 2.5rem;">' +
                    '<div id = SelectPicDiv2 style="' + buttonStyle + 'position:absolute;background-image: url(images/buttonStyle.png);left: 30.6%; width: 39%; top: 0%; height: 100%; font-size: 1rem; color: white; border: 0px; line-height: 2.5; text-align: center;" >选择图片</div>' +
                    '<input id="SelectPicButton2" type="file"  style="position:absolute; left:30%; width:40%; top:0%; height:100%;opacity:0" accept="image/*;capture=camera" />' +
                    '<input id="MaskControl" type="button" value="预览"  style="' + buttonStyle + 'left:0.2%; width:30%; top:0%; height:100%;font-size:1rem;color:white;background-image: url(images/buttonStyle.png);"/>' +
                    '<input id="Confirm"  type="button" value="确定" style="' + buttonStyle + 'left:70%; width:30%; top:0%; height:100%;font-size:1rem;color:white;background-image: url(images/buttonStyle.png);" />' +
                    '</div>' +
                    '<div style="position:absolute; left:1000%; width:100%; top:0%; height:85%; background-color:#00ff00" >' +
                    '<canvas id="ClipCanvas" style="background-color:#ccc; display: block ;position:absolute; left:0%; width:100%; top:0%; height:100%;"></canvas>' +
                    '</div>' +
                    '<div style="position:absolute; left:0%; width:100%; top:0%; height:100%;background-image: url(images/phoneBg.png);background-size:cover;" id="FirstSelect">' +
                    '<div id = SelectPicDiv1 style="text-align: center;position:absolute; left:0%; width:100%; top:0%; height:80%; font-size: 1.4rem;color: white" >点击此处选择图片</div>' +
                    '<input id="SelectPicButton1" type="file" style="' + buttonStyle + ' left:0%; width:100%; top:0%; height:80%;opacity:0" accept="image/*;capture=camera" />' +
                    '<input id="Cancel1" type="button" value="取消"  style="' + buttonStyle + 'left:0%; width:16rem;bottom: 0;height: 3rem;font-size:1.2rem;color:white;background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#a4a4a4), to(#888888));background-image: url(images/buttonStyle.png);"  />' +
                    '</div>';
            }   else
            {
                fileDiv.innerHTML =
                    '<div style="position:absolute;left: 0; top: 0; bottom: 0; right: 0;" id="PicArea" >' +
                    '<canvas id="EditCanvas" style="background-image: url(images/phoneBg.png);display: block ;position:absolute; left:0%; width:100%; top:0%; height:100%;background-size:cover;"></canvas>' +
                    '<input id="Cancel2" type="button" value="取消" style="' + buttonStyle + 'right:0;width: 3.5rem; top:5%; color:white;height:2rem;font-size: 1rem;background-image: url(images/buttonStyle.png);;background-size:cover;"/>' +
                    '</div>' +
                    '<div style="position:absolute; left:0%; width:100%;bottom: 0; height: 2.5rem;">' +
                    '<div id = SelectPicDiv2 style="' + buttonStyle + 'position:absolute;background-image: url(images/buttonStyle.png);background-size:cover;left: 30.6%; width: 39%; top: 0%; height: 100%; font-size: 1rem; color: white; border: 0px; line-height: 2.5; text-align: center;" >选择图片</div>' +
                    '<input id="SelectPicButton2" type="file"  style="background-color:transparent;position:absolute; left:30%; width:40%; top:0%; height:100%;opacity:0" accept="image/*;capture=camera" />' +
                    '<input id="MaskControl" type="button" value="预览"  style="' + buttonStyle + 'left:0.2%; width:30%; top:0%; color:white;height:100%;font-size: 1rem;background-image: url(images/buttonStyle.png);;background-size:cover;background-color:transparent;"/>' +
                    '<input id="Confirm"  type="button" value="确定" style="' + buttonStyle + 'left:70%; width:30%; top:0%;color:white; height:100%;font-size:1rem;background-image: url(images/buttonStyle.png);;background-size:cover;background-color:transparent;" />' +
                    '</div>' +
                    '<div style="position:absolute; left:1000%; width:100%; top:0%; height:85%; background-color:#00ff00" >' +
                    '<canvas id="ClipCanvas" style="background-color:#ccc; display: block ;position:absolute; left:0%; width:100%; top:0%; height:100%;"></canvas>' +
                    '</div>' +
                    '<div style="position:absolute; left:0%; width:100%; top:0%; height:100%;background-image: url(images/phoneBg.png);background-size:cover;" id="FirstSelect">' +
                    '<div id = SelectPicDiv1 style="text-align: center;position:absolute; left:0%; width:100%; top:0%; height:80%;;color: white; font-size: 1.4rem;" >点击此处选择图片</div>' +
                    '<input id="SelectPicButton1" type="file" style="' + buttonStyle + ' left:0%; width:100%; top:0%; height:80%;opacity:0" accept="image/*;capture=camera" />' +
                    '<input id="Cancel1" type="button" value="取消" style="' + buttonStyle + 'left:0%; width:16rem;bottom: 0;height: 3rem;color:white;font-size:1.2rem;background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#a4a4a4), to(#888888));background-image: url(images/buttonStyle.png);background-size:cover;"  />' +
                    '</div>';
            }

	}
	
	function fitWindow() //函数：获取尺寸
    {
		var fileDiv = document.getElementById(fileDivName);
		fileDiv.style.display = "inline";
		
		editCanvas = document.getElementById('EditCanvas');
		editCanvas.width = editCanvas.clientWidth;
		editCanvas.height = editCanvas.clientHeight;


		editContext = editCanvas.getContext("2d");
		
		picAreaWidth = editCanvas.clientWidth;
		picAreaHeight = editCanvas.clientHeight;

		picClipWidth = picAreaWidth * clipAreaSizeR;
		picClipLeft = (picAreaWidth - picClipWidth) / 2;
		picClipHeight = picClipWidth * clipAreaLengthWidthRatio;
		picClipTop = (picAreaHeight - picClipHeight) / 2;
		
		if (picClipTop < 0) {
			picClipTop = 0;
			picClipHeight = picAreaHeight;
		}
		
        var maskCount = 1;
        for(var i = 0; i < maskCount; ++i)
        {
            centerMaskImageList[i] = new Image();
            centerMaskImageList[i].src="images/center" + i + ".png";
        }
		centerMaskImage = centerMaskImageList[curSelectMaskIndex];
		
		frameMaskImage.src = "images/frame.png";
		
		maskCanvas = document.createElement('canvas');
		maskContext = maskCanvas.getContext("2d");
		maskCanvas.width = editCanvas.width;
		maskCanvas.height = editCanvas.height;
		
		// text align
		var selectPicDiv = document.getElementById("SelectPicDiv1");
		selectPicDiv.style.lineHeight = selectPicDiv.offsetHeight + 'px';
		selectPicDiv = document.getElementById("SelectPicDiv2");
		selectPicDiv.style.lineHeight = selectPicDiv.offsetHeight + 'px';
        selectPicDiv.src = "images/phoneBg.png";
		
		fileDiv.style.display = "none";
	}
	
	function bindEvent() {
		var plat = checkPlatForm();
		var touchstart = 'touchstart';
		if (plat == 'PC') {
			editCanvas.addEventListener('mousedown', doMouseDown, true);
			editCanvas.addEventListener('mousemove', doMouseMove, false);
			editCanvas.addEventListener('mouseup', doMouseUp, false);
			editCanvas.addEventListener('mousewheel', doMouseWheel, false);
			touchstart = 'click';
		}
		else if (plat == 'Mobile') {
			document.addEventListener('touchstart', onTouchStart, false);
			document.addEventListener('touchmove', onTouchMove, false);
			document.addEventListener('touchend', onTouchEnd, false);
		}

        document.getElementById('SelectPicButton1').addEventListener('change', onFileSelected, false);
        document.getElementById('SelectPicButton2').addEventListener('change', onFileSelected, false);
        document.getElementById('Confirm').addEventListener(touchstart, onClickConfirm, false);
        document.getElementById('Cancel1').addEventListener(touchstart, onClickCancel, false);
        document.getElementById('Cancel2').addEventListener(touchstart, onClickCancel, false);
        document.getElementById('MaskControl').addEventListener(touchstart, onClickMaskControl, false);
	}
	
	function updatePicSize() {
		var maxPicSize = 2000;
		if (picWidth > maxPicSize && picWidth > picHeight) {
			picHeight = picHeight * maxPicSize / picWidth;
			picWidth = maxPicSize;
		}
		else if (picHeight > maxPicSize && picWidth < picHeight) {
			picWidth = picWidth * maxPicSize / picHeight;
			picHeight = maxPicSize;
		}
	}
	
	function onFileSelected(buttonName) {
        var buttonName = event.target.id;

		var oFile = document.getElementById(buttonName).files[0];

		picLoading = true;
		var oReader = new FileReader();
		oReader.onload = function (e) {
			
			var picImage = new Image();

			picImage.onload = function () {
				picWidth = picImage.width;
				picHeight = picImage.height;
				
				updatePicSize();
				
				picCanvas.width = picWidth;
				picCanvas.height = picHeight;
				
				var drawContext = picCanvas.getContext('2d');
				
				// search image edge pixel position in case it is squashed vertically. begin
				drawContext.drawImage(picImage, 0, 0, 1, picImage.height, 0, 0, 1, picHeight);
				var data = drawContext.getImageData(0, 0, 1, picHeight).data;
				
				var ratio = 1;
				for (var checkPos = picHeight - 1;checkPos >= 0;checkPos--) {
					var alpha = data[(checkPos) * 4 + 3];
					if (alpha != 0) {
						ratio = (checkPos + 1) / picHeight;
						break;
					}
				}
				// end
				
				drawContext.drawImage(picImage, 0, 0, picImage.width, picImage.height, 0, 0, picWidth, picHeight / ratio);
				
				picPosX = 0;
				picPosY = 0;
				picScale = 1;
				picRotateAngle = 0;

				picLoading = false;
				maskAlpha = 122;
				updateMask(maskAlpha);
				drawImage();
				
				document.getElementById('FirstSelect').style.left = "10000px";
				document.getElementById('FirstSelect').style.display = "none";
			};
			picImage.src = "data:image/*;" + e.target.result.substr(5, e.target.result.length - 5);
		};

		oReader.readAsDataURL(oFile);
	}
	
	function onClickNextMask() {
		curSelectMaskIndex++;
		if (curSelectMaskIndex >= centerMaskImageList.length) {
			curSelectMaskIndex = 0;
		}
		
		centerMaskImage = centerMaskImageList[curSelectMaskIndex];
		
		updateMask(maskAlpha);
		drawImage();
	}
	
	function onClickMaskControl() {
		if (maskAlpha === 255) {
			document.getElementById('MaskControl').value = "预览";
			maskAlpha = 122;
		}
		else {
			document.getElementById('MaskControl').value = "原图";
			maskAlpha = 255;
		}
		
		updateMask(maskAlpha);
		drawImage();
	}
	
	function onClickCancel() {
		document.getElementById(fileDivName).style.display = "none";
		PicEditor.singleton.onCancel();
	}
	
	function drawImage() {
		if (picLoading === true) {
			return;
		}
		
		editContext.clearRect(0, 0, editCanvas.width, editCanvas.height);
		
		
        var img = new Image();
        img.src = 'images/phoneBg.png';
		editContext.fillRect(0, 0, editCanvas.width, editCanvas.height);
        editContext.drawImage(img, 0,0,editCanvas.width,editCanvas.height);

		// draw pic
		editContext.save();
		editContext.translate(picPosX, picPosY);
		editContext.rotate(picRotateAngle);

		editContext.drawImage(picCanvas, 0, 0, picWidth * picScale, picHeight * picScale);
		editContext.restore();
		
		// draw mask
		editContext.drawImage(maskCanvas, 0, 0, editCanvas.width, editCanvas.height);
	}
	
	function updateMask(alpha) {
		maskCanvas.width = editCanvas.width;
		maskCanvas.height = editCanvas.height;
		
		maskContext.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
		maskContext.drawImage(centerMaskImage, picClipLeft, picClipTop, picClipWidth, picClipHeight);
		maskContext.drawImage(frameMaskImage, 0, 0, picClipLeft, picAreaHeight);
		maskContext.drawImage(frameMaskImage, picClipLeft + picClipWidth, 0, picClipLeft, picAreaHeight);
		maskContext.drawImage(frameMaskImage, picClipLeft, 0, picClipWidth, picClipTop);
		maskContext.drawImage(frameMaskImage, picClipLeft, picClipTop + picClipHeight, picClipWidth, picClipTop);
		
		var maskImageData = maskContext.getImageData(0, 0, maskCanvas.width, maskCanvas.height);
		for (var i = 0, n = maskImageData.data.length;i < n;i += 4) {
			if (maskImageData.data[i + 3] != 0) {
				maskImageData.data[i + 3] = alpha;
			}
		}
		maskContext.putImageData(maskImageData, 0, 0);
	}
	
	function getAngle(x1, y1, x2, y2) {
		return Math.atan2(y2 - y1, x2 - x1);
	}
	
	function onClickConfirm() {
		var clipCanvas = document.getElementById('ClipCanvas');
		
		var clipContext = clipCanvas.getContext("2d");
		clipCanvas.width = GameConfig.curWidth();/// clipPicWidth;
		clipCanvas.height = GameConfig.curWidth();/// clipCanvas.width * clipAreaLengthWidthRatio;
		
		var scale = clipCanvas.width / picClipWidth;
		
		clipContext.save();
		clipContext.translate((picPosX - picClipLeft) * scale, (picPosY - picClipTop) * scale);
		clipContext.rotate(picRotateAngle);
		clipContext.drawImage(picCanvas, 0, 0, picWidth * picScale * scale, picHeight * picScale * scale);
		clipContext.restore();
		
		var imageData = clipContext.getImageData(0, 0, clipCanvas.width, clipCanvas.height);
		
		clipContext.clearRect(0, 0, clipCanvas.width, clipCanvas.height);
		
		clipContext.drawImage(centerMaskImage, 0, 0, clipCanvas.width, clipCanvas.height);
		var maskData = clipContext.getImageData(0, 0, clipCanvas.width, clipCanvas.height);
		
		for (var i = 0, n = maskData.data.length;i < n;i += 4) {
			if (maskData.data[i + 3] != 0) {
				imageData.data[i + 3] = 0;
			}
		}
		
		clipContext.putImageData(imageData, 0, 0);
		
		PicEditor.singleton.onLoaded();
		
		document.getElementById(fileDivName).style.display = "none";
	}
	
	
	//----------------------------------PC--------------------------------------------------------------------//
	function doMouseDown(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		mouseStarted = true;
		
		preXPos = event.pageX;
		preYPos = event.pageY;
	}
	
	function doMouseMove(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		if (mouseStarted === false) {
			return;
		}
		
		if (isNaN(event.pageX) || isNaN(event.pageY)) {
			return;
		}
		
		picPosX += (event.pageX - preXPos);
		picPosY += (event.pageY - preYPos);
		preXPos = event.pageX;
		preYPos = event.pageY;
		
		drawImage();
	}
	
	function doMouseUp(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		mouseStarted = false;
	}
	
	function doMouseWheel(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		var oldScale = picScale;
		if (event.wheelDelta > 0) {
			picScale += 0.1;
		}
		else {
			picScale -= 0.1
		
		}
		
		if (picScale < 0.1) {
			picScale = 0.1;
		}
		
		var scaleRate = picScale / oldScale;
		picPosX = event.pageX - (event.pageX - picPosX) * scaleRate;
		picPosY = event.pageY - (event.pageY - picPosY) * scaleRate;
		
		drawImage();
	}
	
	//----------------------------------mobile--------------------------------------------------------------------//
	function onTouchStart(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		event.preventDefault();
		mouseStarted = true;
		
		if (event.touches.length == 2) {
			if (isNaN(event.touches[0].pageX) || isNaN(event.touches[0].pageY) || isNaN(event.touches[1].pageX) || isNaN(event.touches[1].pageY)) {
				return;
			}
			
			oldTwoTouchDis = distance(event.touches[0].pageX, event.touches[0].pageY, event.touches[1].pageX, event.touches[1].pageY);
			oldCenterX = (event.touches[0].pageX + event.touches[1].pageX) / 2;
			oldCenterY = (event.touches[0].pageY + event.touches[1].pageY) / 2;
			oldTouchAngle = getAngle(event.touches[0].pageX, event.touches[0].pageY, event.touches[1].pageX, event.touches[1].pageY);
		}
		else if (event.touches.length == 1) {
			if (isNaN(event.touches[0].pageX) || isNaN(event.touches[0].pageY)) {
				return;
			}
			
			preXPos = event.touches[0].pageX;
			preYPos = event.touches[0].pageY;
		}
	}
	
	function onTouchMove(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		if (mouseStarted === false) {
			return;
		}
		
		if (event.touches.length == 2) {
			if (isNaN(event.touches[0].pageX) || isNaN(event.touches[0].pageY) || isNaN(event.touches[1].pageX) || isNaN(event.touches[1].pageY)) {
				return;
			}
			
			// calc scale for this time
			var curTowTouchDis = distance(event.touches[0].pageX, event.touches[0].pageY, event.touches[1].pageX, event.touches[1].pageY);
			var scaleRate = curTowTouchDis / oldTwoTouchDis;
			picScale = picScale * scaleRate;
			oldTwoTouchDis = curTowTouchDis;
			
			// calc rotate angle
			var newCenterX = (event.touches[0].pageX + event.touches[1].pageX) / 2;
			var newCenterY = (event.touches[0].pageY + event.touches[1].pageY) / 2;
			
			var newAngle = getAngle(event.touches[0].pageX, event.touches[0].pageY, event.touches[1].pageX, event.touches[1].pageY);
			var offsetAngle = newAngle - oldTouchAngle;
			oldTouchAngle = newAngle;
			picRotateAngle = picRotateAngle + offsetAngle;
			
			// calc pic pos
			var oldDisPosToTouchCenter = distance(oldCenterX, oldCenterY, picPosX, picPosY);
			var newDisPosToTouchCenter = oldDisPosToTouchCenter * scaleRate;
			
			var oldAnglePosToTouchCenter = getAngle(oldCenterX, oldCenterY, picPosX, picPosY);
			var anglePosToTouchCenter = oldAnglePosToTouchCenter + offsetAngle;
			picPosX = newCenterX + Math.cos(anglePosToTouchCenter) * newDisPosToTouchCenter;
			picPosY = newCenterY + Math.sin(anglePosToTouchCenter) * newDisPosToTouchCenter;
			
			drawImage();
			
			oldCenterX = newCenterX;
			oldCenterY = newCenterY;
		}
		else if (event.touches.length = 1) {
			if (isNaN(event.touches[0].pageX) || isNaN(event.touches[0].pageY)) {
				return;
			}
			
			picPosX += (event.touches[0].pageX - preXPos);
			picPosY += (event.touches[0].pageY - preYPos);
			preXPos = event.touches[0].pageX;
			preYPos = event.touches[0].pageY;
			
			drawImage();
		}
	}
	
	function onTouchEnd(event) {
		if (event.target.id != "EditCanvas") {
			return;
		}
		
		if (event.touches.length == 0) {
			mouseStarted = false;
		}
		else if (event.touches.length == 1) {
			preXPos = event.touches[0].pageX;
			preYPos = event.touches[0].pageY;
		}
	}
	
	function distance(x1, y1, x2, y2) {
		return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
	}
	
	function checkPlatForm() {
		var p = navigator.platform;
		system.win = p.indexOf("Win") == 0;
		system.mac = p.indexOf("Mac") == 0;
		system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
		if (system.win || system.mac || system.xll) {
			return 'PC'
		
		}
		else {
			return 'Mobile'
		
		}
	}
	
	init();
})();